package com.lancoo.answer.view.result

import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.lancoo.answer.R
import com.lancoo.answer.databinding.EvFragmentResultCognitiveBinding
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.CognitiveBean
import com.lancoo.answer.util.*
import com.lancoo.answer.view.base.BaseVMFragment
//import com.lancoo.answer.view.dialog.DialogLevelUp

/*
* add by wgl
* todo 单独封装 只显示认知和预估成绩的view
* */
class ResultCognitiveFragmnet : BaseVMFragment<EvFragmentResultCognitiveBinding>() {

    private var scoreSoundUtils: ScoreSoundUtils? = null
    private var isShowSoundAnim: Boolean = true
    private lateinit var cognitiveBean: CognitiveBean

    companion object {
        private var mIsShowCognition: Boolean = false
        fun loadFragment(isShowCognition: Boolean?): ResultCognitiveFragmnet? {
            val resultFragment = ResultCognitiveFragmnet()
            mIsShowCognition = isShowCognition!!
            return resultFragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_result_cognitive
    }


    override fun initView(view: View) {

        //获取测试数据
        cognitiveBean = ConstantBean.cognitiveBean!!

        //todo 加载中部认知分和预估成绩
        if (mIsShowCognition) {
            mBinding.LlCognitiveView.visibility = View.VISIBLE
            showResultCognitiveView(cognitiveBean)
        } else {
            mBinding.LlCognitiveView.visibility = View.GONE
        }

    }

    /*
    * 显示认知view
    * */
    private fun showResultCognitiveView(cognitiveBean: CognitiveBean) {
        //认知诊断加载动画加载
        Glide.with(this).load(R.raw.ev_loading_cognitive)
                .into(mBinding.IvLoadingCognitive)
        val mLlLoadingCognitive = mBinding.LlLoadingCognitive
        val mLlCognitiveView = mBinding.LlCognitiveView
        val mTvCognitiveIndex = mBinding.TvCognitiveIndex
        val mTvEstimateScore = mBinding.TvEstimateScore
        val mViewCognitionProgress1 = mBinding.ViewCognitionProgress1
        val mViewCognitionProgress2 = mBinding.ViewCognitionProgress2
        val mViewCognitionProgress3 = mBinding.ViewCognitionProgress3
        val mViewCognitionProgress4 = mBinding.ViewCognitionProgress4
        val mViewEstimateProgress1 = mBinding.ViewEstimateProgress1
        val mViewEstimateProgress2 = mBinding.ViewEstimateProgress2
        val mViewEstimateProgress3 = mBinding.ViewEstimateProgress3
        val mViewEstimateProgress4 = mBinding.ViewEstimateProgress4
        val mBlChangeCognitive = mBinding.BlChangeCognitive
        val mBlChangeEstimate = mBinding.BlChangeEstimate
        val mTvChangeCognitive = mBinding.TvChangeCognitive
        val mTvChangeEstimate = mBinding.TvChangeEstimate
        val mRlScaleCognitive = mBinding.RlScaleCognitive
        val mRlScaleEstimate = mBinding.RlScaleEstimate


        mLlLoadingCognitive.visibility = View.VISIBLE
        mLlCognitiveView.visibility = View.GONE

        //加载任务
        val returnFlag = cognitiveBean.CognitionInfo?.ReturnFlag
        if (returnFlag!!) {
            mLlLoadingCognitive.visibility = View.GONE
            mLlCognitiveView.visibility = View.VISIBLE

            val currCognitiveGradeName = cognitiveBean.CognitionInfo?.CurrCognitiveGradeName
            val lastCognitiveGradeName = cognitiveBean.CognitionInfo?.LastCognitiveGradeName
            val passRate = cognitiveBean.CognitionInfo?.PassRate
            val currCognitiveIndex = cognitiveBean.CognitionInfo?.CurrCognitiveIndex
            val lastCognitiveIndex = cognitiveBean.CognitionInfo?.LastCognitiveIndex
            val currEstimateScore = cognitiveBean.CognitionInfo?.CurrEstimateScore
            val lastEstimateScore = cognitiveBean.CognitionInfo?.LastEstimateScore
            val cognitiveRangeListSize = cognitiveBean.CognitionInfo?.CognitiveRangeList?.size
            val maxCognitiveRange =
                    cognitiveBean.CognitionInfo?.CognitiveRangeList!![cognitiveRangeListSize!! - 1]
            val estimateScoreRangeListSize =
                    cognitiveBean.CognitionInfo?.EstimateScoreRangeList?.size
            val maxScoreRange =
                    cognitiveBean.CognitionInfo?.EstimateScoreRangeList!![estimateScoreRangeListSize!! - 1]

            //显示徽章升级动画：若等级提升则显示恭喜弹窗
//            var currLevel = (AsciiUtils.stringToAscii(currCognitiveGradeName).toInt() - 65)
//            var lastLevel = (AsciiUtils.stringToAscii(lastCognitiveGradeName).toInt() - 65)
//            if (currLevel < lastLevel) {
//                Handler().postDelayed({
//                    scoreSoundUtils!!.playSound(1)
//                }, 100)
//                val dialogLevelUp = DialogLevelUp(requireContext(), currLevel)
//                dialogLevelUp.show()
//            }

            //显示认知积分变化&预估成绩变化
            mTvCognitiveIndex.text = DoubleUtils.killlingDouble(
                    DoubleUtils.formatDouble(
                            currCognitiveIndex!!.toDouble(),
                            1
                    )
            )
            mTvCognitiveIndex.typeface =
                    Typeface.createFromAsset(
                            requireContext().assets,
                            "fonts/DIN Condensed Bold.ttf"
                    )
            //显示认知积分变化进度及浮标
            var widthA = 0
            Handler().post {
                widthA = mViewCognitionProgress1.width
                var lastCognitiveIndexWidth =
                        (widthA * lastCognitiveIndex!! / maxCognitiveRange.toInt()).toInt()
                var currentCognitiveIndexWith =
                        (widthA * currCognitiveIndex!! / maxCognitiveRange.toInt()).toInt()

                //显示蓝色进度条
                val params =
                        mViewCognitionProgress2.layoutParams as RelativeLayout.LayoutParams
                if (currCognitiveIndex > lastCognitiveIndex) {
                    val addWidth = currentCognitiveIndexWith - lastCognitiveIndexWidth
                    if (addWidth < 20) {
                        currentCognitiveIndexWith += 20
                    }
                    params.width = currentCognitiveIndexWith
                } else {
                    val addWidth = lastCognitiveIndexWidth - currentCognitiveIndexWith
                    if (addWidth < 20) {
                        lastCognitiveIndexWidth += 20
                    }
                    params.width = lastCognitiveIndexWidth
                }
                mViewCognitionProgress2.layoutParams = params

                if (currCognitiveIndex > lastCognitiveIndex) {
                    //显示绿色增长进度条
                    val params =
                            mViewCognitionProgress3.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = currentCognitiveIndexWith - lastCognitiveIndexWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(lastCognitiveIndexWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewCognitionProgress3.layoutParams = params
                    //显示绿色气泡增长值
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#22d7bb")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))

                    mTvChangeCognitive.text = "+" +
                            DoubleUtils
                                    .round(
                                            DoubleUtils
                                                    .sub(
                                                            currCognitiveIndex.toDouble(),
                                                            lastCognitiveIndex.toDouble()
                                                    ), 0
                                    ).toInt()


                    if (lastCognitiveIndex <= maxCognitiveRange.toInt() / 2) {
                        mBlChangeCognitive.lookPosition = 0//箭头再左侧
                        mBlChangeCognitive.x =
                                (20 + lastCognitiveIndexWidth + (currentCognitiveIndexWith - lastCognitiveIndexWidth) / 2).toFloat()
                    } else {
                        mBlChangeCognitive.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthGreen = mTvChangeCognitive.width
                            mBlChangeCognitive.x =
                                    (20 + lastCognitiveIndexWidth + (currentCognitiveIndexWith - lastCognitiveIndexWidth) / 2).toFloat() - widthGreen - 10
                        }
                    }
                    mBlChangeCognitive.visibility = View.VISIBLE
                }
                if (currCognitiveIndex < lastCognitiveIndex) {
                    //显示红色衰减进度条
                    val params =
                            mViewCognitionProgress4.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = lastCognitiveIndexWidth - currentCognitiveIndexWith
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(currentCognitiveIndexWith, 0, 0, 0)//设置增长的进度条位置
                    mViewCognitionProgress4.layoutParams = params
                    //显示红色气泡减少值
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#ff4d4d")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeCognitive.text = "-" + Math.abs(
                            DoubleUtils.round(
                                    DoubleUtils.sub(
                                            currCognitiveIndex.toDouble(),
                                            lastCognitiveIndex.toDouble()
                                    ), 0
                            ).toInt()
                    )


                    if (lastCognitiveIndex <= maxCognitiveRange.toInt() / 2) {
                        mBlChangeCognitive.lookPosition = 0//箭头再左侧
                        mBlChangeCognitive.x =
                                (20 + currentCognitiveIndexWith + (lastCognitiveIndexWidth - currentCognitiveIndexWith) / 2).toFloat()
                    } else {
                        mBlChangeCognitive.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthRed = mTvChangeCognitive.width
                            mBlChangeCognitive.x =
                                    (20 + currentCognitiveIndexWith + (lastCognitiveIndexWidth - currentCognitiveIndexWith) / 2).toFloat() - widthRed - 10
                        }
                    }
                    mBlChangeCognitive.visibility = View.VISIBLE
                }
                if (currCognitiveIndex == lastCognitiveIndex) {
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#00afff")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeCognitive.text = "暂无变化"

                    mBlChangeCognitive.x = (20 + currentCognitiveIndexWith / 2).toFloat()
                    mBlChangeCognitive.visibility = View.VISIBLE
                }

                var list = ArrayList<String>(cognitiveRangeListSize)
                for (i in 0 until cognitiveRangeListSize) {
                    val scoreScale = cognitiveBean.CognitionInfo?.CognitiveRangeList!![i]
                    list.add("" + scoreScale)
                }
                var listFlag = ArrayList<String>(cognitiveRangeListSize)
                for (i in 0 until cognitiveRangeListSize) {
                    if (i == (cognitiveRangeListSize - 1)) {
                        listFlag.add("")
                    } else {
                        val scale = ((65 + cognitiveRangeListSize - 2) - i).toChar().toString()
                        listFlag.add(scale)
                    }
                }
                mRlScaleCognitive.removeAllViews()
                showScaleX(mRlScaleCognitive, widthA, list, listFlag)
            }

            //显示预估成绩变化进度及浮标
            mTvEstimateScore.text = DoubleUtils.killlingDouble(
                    DoubleUtils.formatDouble(
                            currEstimateScore!!.toDouble(),
                            1
                    )
            )
            mTvEstimateScore.typeface =
                    Typeface.createFromAsset(
                            requireContext().assets,
                            "fonts/DIN Condensed Bold.ttf"
                    )
            var widthB = 0
            Handler().post {
                widthB = mViewEstimateProgress1.width

                var lastEstimateScoreWidth =
                        (widthB * lastEstimateScore!! / maxScoreRange.toInt()).toInt()
                var currEstimateScoreWidth =
                        (widthB * currEstimateScore!! / maxScoreRange.toInt()).toInt()

                //显示黄色进度条
                val params =
                        mViewEstimateProgress2.layoutParams as RelativeLayout.LayoutParams
                if (currEstimateScore > lastEstimateScore) {
                    val addWidth = currEstimateScoreWidth - lastEstimateScoreWidth
                    if (addWidth in 1..19) {
                        currEstimateScoreWidth += 20
                    }
                    params.width = currEstimateScoreWidth
                } else {
                    val addWidth = lastEstimateScoreWidth - currEstimateScoreWidth
                    if (addWidth in 1..19) {
                        lastEstimateScoreWidth += 20
                    }
                    params.width = lastEstimateScoreWidth
                }
                mViewEstimateProgress2.layoutParams = params

                if (currEstimateScore > lastEstimateScore) {
                    //显示绿色增长进度条
                    val params =
                            mViewEstimateProgress3.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = currEstimateScoreWidth - lastEstimateScoreWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(lastEstimateScoreWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewEstimateProgress3.layoutParams = params
                    //显示绿色气泡增长值
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#22d7bb")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "+" + DoubleUtils
                            .round(
                                    DoubleUtils
                                            .sub(
                                                    currEstimateScore.toDouble(),
                                                    lastEstimateScore.toDouble()
                                            ), 0
                            ).toInt()


                    if (lastEstimateScore <= maxScoreRange.toInt() / 2) {
                        mBlChangeEstimate.lookPosition = 0//箭头再左侧
                        mBlChangeEstimate.x =
                                (20 + lastEstimateScoreWidth + (currEstimateScoreWidth - lastEstimateScoreWidth) / 2).toFloat()
                    } else {
                        mBlChangeEstimate.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthGreen = mBlChangeEstimate.width
                            mBlChangeEstimate.x =
                                    (20 + lastEstimateScoreWidth + (currEstimateScoreWidth - lastEstimateScoreWidth) / 2).toFloat() - widthGreen + 10
                        }
                    }
                    mBlChangeEstimate.visibility = View.VISIBLE
                }
                if (currEstimateScore < lastEstimateScore) {
                    //显示红色衰减进度条
                    val params =
                            mViewEstimateProgress4.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = lastEstimateScoreWidth - currEstimateScoreWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(currEstimateScoreWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewEstimateProgress4.layoutParams = params
                    //显示红色气泡减少值
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#ff4d4d")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "-" +
                            Math.abs(
                                    DoubleUtils.round(
                                            DoubleUtils.sub(
                                                    currEstimateScore.toDouble(),
                                                    lastEstimateScore.toDouble()
                                            ), 0
                                    ).toInt()
                            )

                    if (lastEstimateScore <= maxScoreRange.toInt() / 2) {
                        mBlChangeEstimate.lookPosition = 0//箭头再左侧
                        mBlChangeEstimate.x =
                                (20 + currEstimateScoreWidth + (lastEstimateScoreWidth - currEstimateScoreWidth) / 2).toFloat()
                    } else {
                        mBlChangeEstimate.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthRed = mBlChangeEstimate.width
                            mBlChangeEstimate.x =
                                    (20 + currEstimateScoreWidth + (lastEstimateScoreWidth - currEstimateScoreWidth) / 2).toFloat() - widthRed + 10
                        }
                    }
                    mBlChangeEstimate.visibility = View.VISIBLE
                }
                if (currEstimateScore == lastEstimateScore) {
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#00afff")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "暂无变化"

                    mBlChangeEstimate.x = (20 + currEstimateScoreWidth / 2).toFloat()
                    mBlChangeEstimate.visibility = View.VISIBLE
                }

                var list = ArrayList<String>(estimateScoreRangeListSize)
                for (i in 0 until estimateScoreRangeListSize) {
                    val scoreScale = cognitiveBean.CognitionInfo?.EstimateScoreRangeList!![i]
                    list.add("" + scoreScale)
                }
                mRlScaleEstimate.removeAllViews()
                showScaleY(mRlScaleEstimate, widthA, list)
            }

        }
    }

    /*
    * 刷新认知view
    * */
    fun refreshResultCognitiveView(mCognitiveBean: CognitiveBean) {
        cognitiveBean = mCognitiveBean
        showResultCognitiveView(cognitiveBean)
    }


    /*
    * 显示进度条刻度(认知积分)
    * */
    private fun showScaleX(
            mRlScaleCognitive: RelativeLayout,
            width_A: Int,
            list: ArrayList<String>,
            listFalg: ArrayList<String>
    ) {
        for (i in 0 until list.size) {
            val mTvScale = TextView(requireContext())
            mTvScale.setTextColor(Color.parseColor("#333333"))
            mTvScale.textSize = 10f
            mTvScale.text = listFalg[i]
            mRlScaleCognitive.addView(mTvScale)
            val bus = MethodUtils.getBusiness(list[i].toDouble(), list[list.size - 1].toDouble())
            if (i == 0) {
                setTextFromLeft(mTvScale, (width_A * bus).toInt())
            } else {
                setTextFromLeft(mTvScale, (width_A * bus).toInt() - 10)
            }
        }
    }

    /*
    * 显示进度条刻度（预估成绩）
    * */
    private fun showScaleY(
            mRlScaleCognitive: RelativeLayout,
            width_A: Int,
            list: ArrayList<String>
    ) {
        for (i in 0 until list.size) {
            val mTvScale = TextView(requireContext())
            mTvScale.setTextColor(Color.parseColor("#333333"))
            mTvScale.textSize = 10f
            mTvScale.text = list[i]
            mRlScaleCognitive.addView(mTvScale)
            val bus = MethodUtils.getBusiness(list[i].toDouble(), list[list.size - 1].toDouble())
            if (i == 0) {
                setTextFromLeft(mTvScale, (width_A * bus).toInt())
            } else {
                setTextFromLeft(mTvScale, (width_A * bus).toInt() - 10)
            }
        }
    }

    private fun setTextFromLeft(Tv: TextView, left: Int) {
        Handler().post {
            //获取控件的宽度
            val tvWidth = Tv.width
            //这里我用FrameLayout布局为列，其他布局设置方法一样，只需改变布局名就行
            val params = Tv.layoutParams as RelativeLayout.LayoutParams
            params.setMargins(left - tvWidth / 2 + 20, 0, 0, 0)
            //改变控件的属性
            Tv.layoutParams = params
        }

    }

    fun hideCognitionInfoView() {
        mBinding.LayoutCognitive.visibility = View.GONE
    }

}